import 'package:flutter/material.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tender_flutter/constant/app_config.dart';
import 'package:tender_flutter/constant/theme_colors.dart';
import 'package:tender_flutter/http/api_response.dart';
import 'package:tender_flutter/page/common/helper/data_manager.dart';
import 'package:tender_flutter/page/home/api/api_collection.dart';
import 'package:tender_flutter/page/home/api/api_home.dart';
import 'package:tender_flutter/page/home/item/tender_list_cell.dart';
import 'package:tender_flutter/page/home/model/common_tag_model.dart';
import 'package:tender_flutter/router/router.dart';
import 'package:tender_flutter/router/router_map.gr.dart';
import 'package:tender_flutter/utils/screen_adaper.dart';
import 'package:tender_flutter/utils/toast.dart';
import 'package:tender_flutter/widgets/load_state_layout.dart';
import 'package:tender_flutter/widgets/part_refresh_widget.dart';

import 'item/tender_tag_cell.dart';
import 'model/tender_entity.dart';

// ignore: must_be_immutable
class TenderListPage extends StatefulWidget {
  /// 标讯类型 参见：Constant
  String tenderType;

  /// 区域code
  int areaCode;

  /// 军队的集中采购和不对采购区分
  int state;

  /// 检索关键词
  String keyword;

  /// 根据关键词是否精确查询
  bool exactQuery;

  TenderListPage(
      {Key key,
      this.tenderType,
      this.areaCode,
      this.state,
      this.keyword,
      this.exactQuery})
      : super(key: key);

  @override
  TenderListPageState createState() => TenderListPageState();
}

class TenderListPageState extends State<TenderListPage>
    with AutomaticKeepAliveClientMixin {
  GlobalKey<PartRefreshWidgetState> _tagGlobalKey = GlobalKey();

  RefreshController _refreshController =
      RefreshController(initialRefresh: false);

  Future<ApiResponse<TenderTagPageEntity>> _future;

  LoadState _loadState = LoadState.State_Loading;

  /// 区域id
  int areaCode;

  /// 关键词
  String keyword;

  /// 发布时间
  String beginTime;

  /// 结束时间
  String endTime;

  /// 最大金额
  String maxMoney;

  /// 最小金额
  String minMoney;

  int page = AppConfig.page;

  int pageCount = AppConfig.pageCount;

  /// 列表数据
  List<TenderList> _dataLists = [];

  /// 标签数据（筛选的标签数据）
  List<CommonTagModel> _tagLists = [];

  /// 选中的筛选标签
  CommonTagModel _selectTagModel;

  ///  是否需要刷新数据
  bool isNeedRefreshData = false;

  bool isInit = false;

  /// 刷新数据
  /// synchronous 是否立即刷新
  void updateData(bool synchronous) {
    if (synchronous) {
      if (_loadState == LoadState.State_Success) {
        if (_refreshController != null && isInit) {
          _refreshController.requestRefresh();
        } else {
          _onRefresh();
        }
      } else {
        _onRefresh();
      }
      isNeedRefreshData = false;
    } else {
      /// 定义需要刷新
      isNeedRefreshData = true;
    }
  }

  ///下拉刷新
  void _onRefresh() {
    isNeedRefreshData = false;
    page = 1;
    setState(() {
      _future = _getData();
    });
  }

  /// 加载更多
  void _onLoading() {
    page += 1;
    setState(() {
      _future = _getData();
    });
  }

  /// 获取数据
  Future<ApiResponse<TenderTagPageEntity>> _getData() async {
    var response = await ApiHome.getTenderList<TenderTagPageEntity>(
        areaCode: areaCode != null
            ? areaCode
            : (widget.areaCode != null
                ? widget.areaCode
                : (DataManager.instance.cityEntity == null
                    ? null
                    : DataManager.instance.cityEntity.id)),
        state: widget.state,
        keyword: keyword != null ? keyword : widget.keyword,
        type: widget.tenderType,
        beginTime: beginTime,
        endTime: endTime,
        maxMoney: maxMoney == "0" ? null : maxMoney,
        minMoney: minMoney == "0" ? null : minMoney,
        page: page,
        pageCount: pageCount,
        isTerm: widget.exactQuery ?? false,
        dynamicParams: _selectTagModel != null
            ? {_selectTagModel.key: _selectTagModel.value}
            : null);
    return response;
  }

  /// 收藏/取消
  /// 返回是否请求成功的状态
  Future<bool> _setCollection({int tenderId}) async {
    var response = await ApiCollection.tenderCollection(tenderId: tenderId);
    ToastUtils.show(response.msg);
    return response.status == Status.SUCCESS ? true : false;
  }

  FutureBuilder<ApiResponse<TenderTagPageEntity>> _buildFutureBuilder() {
    return FutureBuilder(
        future: _future,
        builder: (BuildContext context,
            AsyncSnapshot<ApiResponse<TenderTagPageEntity>> snapshot) {
          if (snapshot.connectionState == ConnectionState.done) {
            if (snapshot.hasData) {
              TenderTagPageEntity pageEntity = snapshot.data.result;

              if (snapshot.data.status == Status.SUCCESS) {
                TenderEntity entity = pageEntity.pageinfo;
                if (_tagLists.isEmpty &&
                    pageEntity.dh != null &&
                    pageEntity.dh.isNotEmpty) {
                  // 如果标签数据不为空，则显示
                  _tagLists = pageEntity.dh;
                  _tagLists.insert(0, CommonTagModel(title: "全部"));
                  _selectTagModel = _tagLists[0];
                }
                List temps = entity.xList == null ? [] : entity.xList;
                page == AppConfig.page
                    ? _dataLists = temps
                    : _dataLists += temps;
                if (_dataLists.isEmpty) {
                  _loadState = LoadState.State_Empty;
                } else {
                  _loadState = LoadState.State_Success;
                }
              } else {
                _loadState = LoadState.State_Error;
              }
            } else if (snapshot.hasError) {
              _loadState = LoadState.State_Error;
            }

            /// 结束刷新，处理分页
            if (_dataLists.length % AppConfig.pageCount != 0) {
              _refreshController.loadNoData();
            } else {
              if (_refreshController.isLoading) {
                _refreshController.loadComplete();
              }
            }
            if (_refreshController.isRefresh) {
              _refreshController.refreshCompleted(resetFooterState: true);
            }
          }

          return _initContentLayut();
        });
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    _future = _getData();
    WidgetsBinding.instance.addPostFrameCallback((mag) {
      isInit = true;
    });
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return _buildFutureBuilder();
  }

  Widget _initContentLayut() {
    return Container(
        child: Column(children: [
      Offstage(
          offstage: _tagLists.isEmpty ? true : false,
          child: Column(children: [
            _initTagList(),
            Container(
              height: ScreenAdapter.height(10),
              color: ThemeColors.colorType11,
            ),
          ])),
      Expanded(
          child: LoadStateLayout(
        state: _loadState,
        successWidget: _initList(),
      ))
    ]));
  }

  /// 标签
  Widget _initTagList() {
    return Container(
      height: ScreenAdapter.height(90),
      width: ScreenAdapter.screenWidth(),
      color: ThemeColors.colorWhite,
      padding: EdgeInsets.symmetric(horizontal: ScreenAdapter.width(30)),
      child: PartRefreshWidget(_tagGlobalKey, () {
        return SingleChildScrollView(
          physics: const BouncingScrollPhysics(),
          scrollDirection: Axis.horizontal,
          child: Wrap(
            direction: Axis.horizontal,
            children: _tagLists
                .map((item) => TenderTagCell(
                      title: item.title,
                      selected: item == _selectTagModel ? true : false,
                      onTap: () {
                        _selectTagModel = item;
                        _tagGlobalKey.currentState.update();
                        widget.exactQuery = true;
                        updateData(true);
                      },
                    ))
                .toList(),
            spacing: ScreenAdapter.width(15),
            alignment: WrapAlignment.start,
          ),
        );
      }),
    );
  }

  /// 列表
  Widget _initList() {
    return SmartRefresher(
        controller: _refreshController,
        enablePullUp: true,
        enablePullDown: true,
        onRefresh: _onRefresh,
        onLoading: _onLoading,
        child: ListView.separated(
          physics: AlwaysScrollableScrollPhysics(),
          itemCount: _dataLists.length,
          itemBuilder: (BuildContext context, int index) {
            TenderList model = _dataLists[index];
            return TenderListCell(
                data: model,
                highlightWords: keyword != null
                    ? [keyword]
                    : (widget.keyword != null ? [widget.keyword] : null),
                onCollection: () async {
                  return await _setCollection(tenderId: model.id);
                },
                onTap: () {
                  LRouter.navigatorCtx(context).push(Routes.tenderDetailPage,
                      queryParams: {"tenderId": model.id.toString()});
                });
          },
          separatorBuilder: (BuildContext context, int index) {
            return Divider(
              height: ScreenAdapter.height(10),
              color: ThemeColors.colorType11,
            );
          },
        ));
  }
}
